package com.example.mediasession;

import android.content.ComponentName;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private static final String  TAG = "MainActivity";
    /**媒体控制器，用于控制媒体播放*/
    private MediaControllerCompat mediaController;
    private TextView titleTextView;
    private TextView artistTextView;
    private TextView statusTextView;
    private Button playPauseButton;
    /** 媒体浏览器，用于浏览和访问媒体内容 */
    private MediaBrowserCompat mediaBrowser;

    private final MediaBrowserCompat.ConnectionCallback connectionCallback =
            new MediaBrowserCompat.ConnectionCallback() {
                @Override
                public void onConnected() {
                    try {
                        MediaSessionCompat.Token token = mediaBrowser.getSessionToken();
                        mediaController = new MediaControllerCompat(MainActivity.this, token);
                        MediaControllerCompat.setMediaController(MainActivity.this, mediaController);
                        mediaController.registerCallback(mediaControllerCallback);

                        // 立即更新UI
                        updatePlaybackState(mediaController.getPlaybackState());
                        updateMetadata(mediaController.getMetadata());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConnectionFailed() {
                    statusTextView.setText("无法连接到媒体服务");
                }

                @Override
                public void onConnectionSuspended() {
                    // 连接中断处理
                }
            };

    private final MediaControllerCompat.Callback mediaControllerCallback =
            new MediaControllerCompat.Callback() {
                @Override
                public void onPlaybackStateChanged(PlaybackStateCompat state) {
                    updatePlaybackState(state);
                }

                @Override
                public void onMetadataChanged(MediaMetadataCompat metadata) {
                    updateMetadata(metadata);
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        titleTextView = findViewById(R.id.titleTextView);
        artistTextView = findViewById(R.id.artistTextView);
        statusTextView = findViewById(R.id.statusTextView);
        playPauseButton = findViewById(R.id.playPauseButton);

        playPauseButton.setOnClickListener(v -> togglePlayback());

        // 初始化 MediaBrowser
        mediaBrowser = new MediaBrowserCompat(
                this,
                new ComponentName(this, MediaService.class),
                connectionCallback,
                null
        );
    }

    @Override
    protected void onStart() {
        super.onStart();
        mediaBrowser.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaController != null) {
            mediaController.unregisterCallback(mediaControllerCallback);
            mediaController = null;
        }
        if (mediaBrowser != null && mediaBrowser.isConnected()) {
            mediaBrowser.disconnect();
        }
    }
    private void togglePlayback() {
        Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
        if (mediaController == null){
            statusTextView.setText("mediaController is null...");
            Log.d(TAG, "mediaController is null...: ");
            return;
        }
        // 获取媒体播放状态
        PlaybackStateCompat state = mediaController.getPlaybackState();
        if (state != null) {
            if (state.getState() == PlaybackStateCompat.STATE_PLAYING) {
                mediaController.getTransportControls().pause();
            } else {
                mediaController.getTransportControls().play();
            }
        }
    }

    private void updatePlaybackState(PlaybackStateCompat state) {
        if (state == null) return;

        switch (state.getState()) {
            case PlaybackStateCompat.STATE_PLAYING:
                statusTextView.setText("状态：正在播放");
                playPauseButton.setText("暂停");
                break;
            case PlaybackStateCompat.STATE_PAUSED:
                statusTextView.setText("状态：已暂停");
                playPauseButton.setText("播放");
                break;
            default:
                statusTextView.setText("状态：" + state.getState());
                break;
        }
    }

    private void updateMetadata(MediaMetadataCompat metadata) {
        if (metadata == null) return;

        titleTextView.setText(metadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
        artistTextView.setText(metadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
    }
}
